import React, { useEffect, useState } from 'react';
import 'antd/dist/reset.css';
import './App.css';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Layout, Menu, theme } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined, ConsoleSqlOutlined } from '@ant-design/icons';
import SQLQueryPage from "./pages/SQLQueryPage";
import SQLEditPage from "./pages/SQLEditPage";

const { Header, Content, Footer, Sider } = Layout;

const defaultKey = '/work/SQLQuery';
const items = [
  { label: "SQL查询", key: "/work/SQLQuery", path: "/work/SQLQuery", icon: <ConsoleSqlOutlined />, component: <SQLQueryPage /> },
  { label: "对象浏览器", key: "/work/SQLEdit", path: "/work/SQLEdit", icon: <ConsoleSqlOutlined />, component: <SQLEditPage /> },
  // {
  //   label: "用户管理",
  //   key: "1",
  //   path: "SubMenuSJSC",
  //   icon: <UserOutlined />,
  //   component: <UserTable />,
  //   children: [
  //     { label: "用户管理", key: "/page/user/edit", path: "/page/user/edit", icon: null, component: <UserTable /> },
  //     { label: "权限管理", key: "/page/user/op", path: "/page/user/op", icon: null, component: <UserOpTable /> },
  //   ],
  // },
  // { label: "部门管理", key: "/page/dept/edit", path: "/page/dept/edit", icon: <ClusterOutlined />, component: <DeptTable /> },
  // { label: "DeepSeek", key: "/page/deepseek/chat", path: "/page/deepseek/chat", icon: <WechatWorkOutlined />, component: <ChatPage /> },
];

// 找到对应的组件并设置为当前组件
function findComponent(items: any[], key: string): JSX.Element | undefined {
  for (const item of items) {
    if (item.key === key) {
      return item.component;
    }
    if (item.children) {
      const foundComponent = findComponent(item.children, key);
      if (foundComponent) {
        return foundComponent;
      }
    }
  }
  return undefined;
};

function findComponentByPath(items: any[], path: string): JSX.Element | undefined {
  for (const item of items) {
    if (item.path === path) {
      return item.component;
    }
    if (item.children) {
      const foundComponent = findComponentByPath(item.children, path);
      if (foundComponent) {
        return foundComponent;
      }
    }
  }
  return undefined;
};

function findMenuItem(items: any[], key: string): any | null {
  for (const item of items) {
    if (item.key === key) return item;
    if (item.children) {
      const found = findMenuItem(item.children, key);
      if (found) return found;
    }
  }
  return null;
};

const App: React.FC = () => {
  const navigate = useNavigate();
  const [currentComponent, setCurrentComponent] = useState<JSX.Element | undefined>();
  const [collapsed, setCollapsed] = useState(() => {
    // 从 localStorage 读取折叠状态，默认为 false
    const savedCollapsed = localStorage.getItem('menuCollapsed');
    return savedCollapsed ? JSON.parse(savedCollapsed) : true;
  });
  const [openKeys, setOpenKeys] = useState(() => {
    // 从 localStorage 读取 openKeys，默认为空数组
    const savedOpenKeys = localStorage.getItem('menuOpenKeys');
    return savedOpenKeys ? JSON.parse(savedOpenKeys) : [];
  });
  const location = useLocation();

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  useEffect(() => {
    // 监听 collapsed 状态的变化，并保存到 localStorage
    localStorage.setItem('menuCollapsed', JSON.stringify(collapsed));

    // 监听 openKeys 的变化，并保存到 localStorage
    localStorage.setItem('menuOpenKeys', JSON.stringify(openKeys));

    setCurrentComponent(findComponentByPath(items, location.pathname));
    if (!findComponentByPath(items, location.pathname)) {
      navigate(defaultKey);
    }
  }, [collapsed, openKeys, location.pathname, navigate]);

  function onMenuClick(e: { key: string }) {
    const component = findComponent(items, e.key);
    if (component) {
      setCurrentComponent(component);
    }

    const menuItem = findMenuItem(items, e.key);
    if (menuItem && menuItem.path) {
      navigate(menuItem.path);
    }
  };

  function onOpenChange (keys: string[]) {
    setOpenKeys(keys);
  };

  return (
    <Layout>
      <Header
        style={{
          padding: 0,
          background: colorBgContainer,
          height: 48,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          position: 'fixed', // 固定位置
          top: 0,            // 距离顶部 0
          left: 0,           // 左边界对齐
          right: 0,          // 右边界对齐
          zIndex: 1000,      // 设置较高的层级，确保在其他内容之上
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '18px',
              width: 48,
              height: 48,
              padding: 0,
            }}
          />
          <span style={{ fontSize: '18px', fontWeight: 'bold', marginLeft: 16, lineHeight: '48px' }}>联合打印</span>
        </div>
      </Header>

      <Content style={{ marginTop: 48 }}>
        <Layout>
          <Sider
            collapsible
            collapsed={collapsed}
            onCollapse={(value) => setCollapsed(value)}
            collapsedWidth={48}
            style={{ position: 'fixed', height: '100vh', left: 0, top: 48, bottom: 0 }}
          >
            <Menu
              theme="dark"
              defaultSelectedKeys={[findComponentByPath(items, location.pathname) ? location.pathname : defaultKey]}
              mode="inline"
              items={items}
              onClick={onMenuClick}
              openKeys={openKeys}
              onOpenChange={onOpenChange}
              style={{ height: '100%', overflow: 'auto' }}
            />
          </Sider>
          <Layout style={{ marginLeft: collapsed ? 48 : 200, transition: 'margin-left 0.3s' }}>
            <Content style={{ margin: '16px 16px 0 16px', minHeight: 'calc(100vh - 64px)' }}>
              <div
                style={{
                  padding: '16px 16px 0 16px',
                  height: '100%',
                  background: colorBgContainer,
                  borderRadius: borderRadiusLG,
                }}
              >
                {/* 100vh - 96px */}
                {currentComponent}
              </div>
            </Content>
            <Footer style={{ textAlign: 'center', height: 64 }}>
              东方晨旭 ©{new Date().getFullYear()}
            </Footer>
          </Layout>
        </Layout>
      </Content>
    </Layout>
  );
};

export default App;